import { fileURLToPath, URL } from 'node:url'

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import VueDevTools from 'vite-plugin-vue-devtools'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'

import { webUpdateNotice } from'@plugin-web-update-notification/vite'

// https://vitejs.dev/config/
export default ({ mode }) =>{
  return defineConfig({
    plugins: [
      VueDevTools(),
      vue(),
      webUpdateNotice({
        versionType: 'build_timestamp',
        notificationProps: {
          title: '📢 系统更新',
          description: '系统更新啦！, 请刷新页面',
          buttonText: '刷新',
          dismissButtonText: "忽略",
        },
      }), 
      AutoImport({
        resolvers: [ElementPlusResolver()],
      }),
      Components({
        resolvers: [ElementPlusResolver()],
      }),
    ],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url))
      }
    },
    build: {
      sourcemap: false,
      minify: 'terser',// 移除生产log配置需要它
      terserOptions: {
        compress: {
          drop_console: mode === 'production' // 生产移除console
        }
      },
      rollupOptions: {
        output: {
          manualChunks(id) {
            if (id.includes('node_modules')) {
              return id
                .toString()
                .split('node_modules/')[1]
                .split('/')[0]
                .toString()
            }
          },
          chunkFileNames: (chunkInfo) => {
            const facadeModuleId = chunkInfo.facadeModuleId
              ? chunkInfo.facadeModuleId.split('/')
              : []
            const fileName =
              facadeModuleId[facadeModuleId.length - 2] || '[name]'
            return `js/${fileName}/[name].[hash].js`
          }
        }
      }
    },
    server: {
      // open: process.platform === 'darwin', // 如果是 mac 平台
      port: 9311,
      // host: '10.5.10.55',
      open: true,
      proxy: {
        '/mock-api': {
          target: 'http://127.0.0.1:4523/m1/3058855-0-default',
          rewrite: (path) => path.replace('/mock-api', ''),
        },
        '/api': {
          target: 'http://127.0.0.1:8888',
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, '')
        },
      }
    }
  })
}

